package com.mate.cloud.auth.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.mate.cloud.core.common.constant.AuthConstant;
import com.mate.cloud.core.util.JwtGeneratorUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.filter.OncePerRequestFilter;


import java.io.IOException;

/**
 * JWT登录授权过滤器
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2024/6/15 10:06
 * @updateUser:     MI
 * @updateTime:     2024/6/15 10:06
 * @updateRemark:   修改内容
 * @version:        v1.0
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authHeader != null && authHeader.startsWith(AuthConstant.JWT_TOKEN_PREFIX)) {
            String authToken = authHeader.substring(AuthConstant.JWT_TOKEN_PREFIX.length());// The part after "Bearer "
            final DecodedJWT decodedJWT = JwtGeneratorUtil.decodeToken(authToken);
            final String username = decodedJWT.getSubject();
            log.info("checking username:{}", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (userDetails == null) {
                    return;
                }
                if (JwtGeneratorUtil.validateToken(authToken)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
//                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
